<?php
namespace app\admin\controller\community;

use app\common\controller\Backend;
use think\Db;
use think\exception\ValidateException;
use think\Exception;

class Teacherpool extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CommunityTeacher');
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        if ($this->request->isAjax()) {
            // 获取请求参数
            $params = $this->request->param();
            $page = $this->request->param('offset') / $this->request->param('limit') + 1;
            $limit = $this->request->param('limit', 10);
            $sort = $this->request->param('sort', 'weigh');
            $order = $this->request->param('order', 'desc');
            
            // 处理搜索条件
            $where = [];
            
            // 处理搜索参数
            $search = $this->request->param('search', '');
            $status = $this->request->param('status', '');
            $keyword = $this->request->param('keyword', '');
            
            // 关键字搜索（姓名/手机号/学校/社区）
            if (!empty($search)) {
                $where[] = ['name|phone|school.name|community.name', 'like', "%{$search}%"];
            }
            
            // 处理搜索表单中的关键字
            if (!empty($keyword)) {
                $where[] = ['name|phone|school.name|community.name', 'like', "%{$keyword}%"];
            }
            
            // 状态筛选
            if ($status !== '') {
                $where[] = ['status', '=', $status];
            }
            
            // 构建查询
            $query = $this->model
                ->with(['school', 'community'])
                ->where($where);
                
            // 获取总数
            $total = $query->count();
            
            // 处理排序
            if (in_array($sort, ['school.name', 'community.name'])) {
                // 关联表排序
                $relation = explode('.', $sort)[0];
                $field = explode('.', $sort)[1];
                $query->alias('t')
                    ->join($relation . ' ' . $relation, 't.' . $relation . '_id = ' . $relation . '.id')
                    ->order($sort . ' ' . $order);
            } else {
                // 主表排序
                $query->order($sort, $order);
            }
            
            // 获取分页数据
            $list = $query->page($page, $limit)->select();
                
            return json(["total" => $total, "rows" => $list]);
        }
        
        return $this->view->fetch();
    }

    public function approve()
    {
        $ids = $this->request->post("ids");
        if ($ids) {
            $this->model->where('id', 'in', $ids)->update(['status' => 1]);
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function reject()
    {
        $ids = $this->request->post("ids");
        if ($ids) {
            $this->model->where('id', 'in', $ids)->update(['status' => 2]);
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 教育背景列表（固定值）
        $educationList = [
            1 => '大专',
            2 => '本科',
            3 => '硕士',
            4 => '博士',
            5 => '其他'
        ];
        
        // 职称列表（固定值）
        $titleList = [
            1 => '助教',
            2 => '讲师',
            3 => '副教授',
            4 => '教授',
            5 => '其他'
        ];

        // 科目列表（示例，实际请根据你的业务调整）
        $subjectList = [
            1 => '语文',
            2 => '数学',
            3 => '英语',
            4 => '物理',
            5 => '化学',
            6 => '生物',
            7 => '政治',
            8 => '历史',
            9 => '地理',
            10 => '其他'
        ];
        
        // 用户列表（从user表获取）
        $userList = \think\Db::name('user')
            ->where('status', 'normal')
            ->column('nickname', 'id');
            
        $this->view->assign([
            'educationList' => $educationList,
            'titleList' => $titleList,
            'subjectList' => $subjectList,
            'userList' => $userList
        ]);
        
        return $this->view->fetch();
    }
    /**
     * 导出数据
     */
    public function export()
    {
        // 获取请求参数
        $params = $this->request->param();
        $sort = $this->request->param('sort', 'weigh');
        $order = $this->request->param('order', 'desc');
        
        // 处理搜索条件
        $where = [];
        
        // 处理搜索参数
        $search = $this->request->param('search', '');
        $status = $this->request->param('status', '');
        $keyword = $this->request->param('keyword', '');
        
        // 关键字搜索（姓名/手机号/学校/社区）
        if (!empty($search)) {
            $where[] = ['name|phone|school.name|community.name', 'like', "%{$search}%"];
        }
        
        // 处理搜索表单中的关键字
        if (!empty($keyword)) {
            $where[] = ['name|phone|school.name|community.name', 'like', "%{$keyword}%"];
        }
        
        // 状态筛选
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        // 构建查询
        $list = $this->model
            ->with(['school', 'community'])
            ->where($where);
            
        // 处理排序
        if (in_array($sort, ['school.name', 'community.name'])) {
            // 关联表排序
            $relation = explode('.', $sort)[0];
            $field = explode('.', $sort)[1];
            $list->alias('t')
                ->join($relation . ' ' . $relation, 't.' . $relation . '_id = ' . $relation . '.id')
                ->order($sort . ' ' . $order);
        } else {
            // 主表排序
            $list->order($sort, $order);
        }
        
        $list = $list->select();
        
        // 表头
        $headList = [
            'id'         => 'ID',
            'name'       => '姓名',
            'phone'      => '手机号',
            'school'     => '所属学校',
            'community'  => '所属社区',
            'teaching_years' => '教龄',
            'status'     => '状态',
            'create_time' => '创建时间'
        ];
        
        // 数据列表
        $dataList = [];
        foreach ($list as $item) {
            $dataList[] = [
                'id' => $item->id,
                'name' => $item->name,
                'phone' => $item->phone,
                'school' => $item->school ? $item->school->name : '',
                'community' => $item->community ? $item->community->name : '',
                'teaching_years' => $item->teaching_years,
                'status' => $item->status_text,
                'create_time' => $item->create_time
            ];
        }
        
        // 导出Excel
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // 设置表头
        $col = 1;
        $row = 1;
        foreach ($headList as $field => $title) {
            $sheet->setCellValueByColumnAndRow($col, $row, $title);
            $col++;
        }
        
        // 填充数据
        $row = 2;
        foreach ($dataList as $data) {
            $col = 1;
            foreach ($headList as $field => $title) {
                $sheet->setCellValueByColumnAndRow($col, $row, $data[$field] ?? '');
                $col++;
            }
            $row++;
        }
        
        // 自动调整列宽
        foreach (range('A', $sheet->getHighestColumn()) as $columnID) {
            $sheet->getColumnDimension($columnID)->setAutoSize(true);
        }
        
        // 设置文件名
        $filename = '教师列表_' . date('YmdHis') . '.xlsx';
        
        // 输出Excel文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }
    
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}